package com.haoqizhe.kernel.security.config;

import cn.hutool.json.JSONUtil;
import com.haoqizhe.kernel.commons.enums.ResultCode;
import com.haoqizhe.kernel.web.result.DefaultErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 访问资源没有权限时的处理
 * @author haoqizhe.li
 * @date 2018/10/18
 **/
@Component
@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        log.error(e.getMessage(),e);

        ResultCode code = ResultCode.PERMISSION_NO_ACCESS;
        HttpStatus status = HttpStatus.UNAUTHORIZED;

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(JSONUtil.toJsonPrettyStr(DefaultErrorResult.failure(code,e, status)));
    }
}
